package io.jenkins.plugins.request;

import io.jenkins.plugins.response.WxResponse;
import io.jenkins.plugins.utils.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

@Slf4j
public class WxRequest {

    private static final CloseableHttpClient httpClient = HttpClients.createDefault();

    private static final String tokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpid}&corpsecret=${corpsecret}";

    private static final String sendAppchatSendUrl = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=${accessToken}";

    public static String getAccessToken(String corpid, String corpsecret) throws IOException {
        HttpGet httpGet = new HttpGet(getTokenUrl(corpid, corpsecret));

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
        WxResponse wxResponse = JSONUtils.readValue(EntityUtils.toString(httpResponse.getEntity()), WxResponse.class);
        return wxResponse == null ? "" : wxResponse.getAccess_token();
    }

    public static boolean sendText(String accessToken, AppchatSendDTO dto) {
        CloseableHttpResponse httpResponse = null;
        boolean success = true;
        try {
            HttpPost httpPost = new HttpPost(getAppChatSendUrl(accessToken));
            httpPost.setEntity(new StringEntity(JSONUtils.writeString(dto), "utf-8"));
            httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                String responseContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
                WxResponse result = JSONUtils.readValue(responseContent, WxResponse.class);
                if (result == null || (result.getErrcode() != 0 && !result.getErrmsg().equals("ok"))) {
                    success = false;
                    log.error("请求发送群聊信息接口返回错误,错误信息：{}", JSONUtils.writeString(result));
                }
            } else {
                success = false;
                log.error("请求发送群聊信息接口返回错误码[" + statusCode + "]");
            }
        } catch (Exception e) {
            success = false;
            log.error("请求发送群聊信息接口返回错误, ", e);
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException ignored) {
                }
            }
        }
        return success;
    }

    private static String getTokenUrl(String corpid, String corpsecret) {
        return tokenUrl.replace("${corpid}", corpid).replace("${corpsecret}", corpsecret);
    }

    private static String getAppChatSendUrl(String accessToken) {
        return sendAppchatSendUrl.replace("${accessToken}", accessToken);
    }
}
